import {decodePage} from "./PageDecoder";
import {actions_const, mutations_const} from "../config/StoreConstant";
import Cmd from "../config/Cmd";
import {loadStrokeInfo} from "./QuestionInfoCache";
import uuid from 'uuid';
import Dexie from 'dexie';

let TotalDB, db;
try {
    TotalDB = new Dexie("three_in_nut");
    TotalDB.version(1).stores({stroke: "++id"});
    db = TotalDB.stroke;
    // console.log(db);
    window.stroke_db = db;
} catch (e) {
    console.log(e)
}
let WebSocketConfig = {};
WebSocketConfig.cmd = {
    WRITE: 0x3,
    NOTIFY: 0x4,
    ON_LINE_STATE: 0x5,
    ADD_DEVICE: 0x20,
    CHECK_ON_LINE_SINGLE: 0x23,
    SET_TIME: 0x40,
    SET_WRITE_STATE: 0x50,

};
// let fileTime = 0;
// let strFile;
// let storePath = "toUpload";
const uploadInterval = 10000;
setTimeout(()=>console.log('数据上报周期 : ' + uploadInterval / 1000 + '秒'), 5000);
// let rtag = 0;
// if (!fs.existsSync(storePath)) {
//
//     fs.mkdirSync(storePath);
// }

WebSocketConfig.sentWsMsg = function (cmd, para) {

    if (!window.ws) {

        window.vueMain.$alert("请检查蓝牙笔设备是否正常开启！");
        return;
    }

    window.ws.send(JSON.stringify({cmd, para}));
};

// let wtag =0;
let handlers = {

    onlineStateHandler(data) {

        /**
         *
         let member = getStoreMemberBySerialNo(WebSocketConfig.macStringfy(data["pen-mac-addr"]));
         member.online = data["para"] !== 0;
         window.vueMain.$store.commit(mutations.UPD_CLASS_MEMBERS_SINGLE, member)
         * **/
    },
    writeHanlder(data) {

        let serialNo = WebSocketConfig.macStringfy(data["pen-mac-addr"]);
        let para = data.para;

        let strokeArr = [];
        let page = data.para['code-page'];
        let id = "0018";
        for (let i = 0; i < data.para['xy-dot-array'].length; i++) {

            let dot = data.para['xy-dot-array'][i];
            if (!dot.x || !dot.y) {
                // console.log('rtag', rtag++);
            }
            let dotDecode = decodePage(page, dot.x, dot.y);
            if (dotDecode) {
                id = dotDecode.id;
                delete dotDecode.id;
                strokeArr.push(dotDecode);
            }
        }
        para['xy-dot-array'] = strokeArr;
        if (strokeArr[0]) {

            para["code-page"] = strokeArr[0].pageCode;
            para["id"] = id;
            para.serialNo = serialNo;
        }
        // if (new Date().getTime() - fileTime > uploadInterval) {
        //
        //     fileTime = new Date().getTime();
        //     strFile = new StrokeStrFileManager(storePath + "/" + fileTime);
        // }
        // strFile.append("|" + JSON.stringify(data.para));
        if (vueMain.$store.state.Member.class.info.id) db.put({
            data: JSON.stringify(data.para),
            class_id: vueMain.$store.state.Member.class.info.id
        });
        // console.log('rtag', rtag++);
    }
};

WebSocketConfig.getHandle = function (cmd) {
    if (cmd === WebSocketConfig.cmd.ON_LINE_STATE) {
        console.log('心跳');
        return handlers.onlineStateHandler
    }
    if (cmd === WebSocketConfig.cmd.WRITE) {
        console.log('收到一笔');
        return handlers.writeHanlder
    }
};

WebSocketConfig.macStringfy = function (mac) {

    let res = "";
    for (let i = 0; i < mac.length; i++) {
        var temp = mac[i] & 0xff;
        res += prefixInteger(temp.toString(16), 2);
    }
    return res;
};

WebSocketConfig.parse = function (str) {

    let res = [];
    if (str.length !== 12) {

        return [0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
    }
    for (let i = 0; i < str.length; i += 2) {

        let temp = str.substr(i, 2);
        res.push(eval("0x" + temp))
    }
    return res;
};

let timer = null, begin = new Date();

function throttle(method, delay, duration) {
    return function () {
        let context = this, args = arguments, current = new Date();
        clearTimeout(timer);
        if (current - begin >= duration) {
            method.apply(context, args);
            begin = current;
        } else {
            timer = setTimeout(function () {
                method.apply(context, args);
            }, delay);
        }
    }
}

let addDevice = function () {


    throttle(() => {
        vueMain.$store.dispatch(actions_const.GET_CLASS_DEVICE_LIST).then(() => {

            setTimeout(() => {
                try {
                    window.ws.send(JSON.stringify({cmd: Cmd.ADD_DEVICE, para: vueMain.$store.getters.deviceMacList}));

                    vueMain.$store.commit(mutations_const.UPD_HAS_ADD_DEVICE, vueMain.$store.state.Member.loginMember.id);
                    // console.log(vueMain.$store.state.Counter.dongleNum);
                    if (1 || vueMain.$store.state.Counter.dongleNum === 2) {
                        setTimeout(() => {

                            // window.ws.send(JSON.stringify({cmd: Cmd.HISTORY_MESSAGE, para: 0x01}))
                        }, 4000);
                    }
                } catch (e) {

                }
            }, 3000)
        })
    }, 4000, 6000)()
};
/**  定时上报  **/
// let uploadNum = 0;
setInterval(() => {
    if (!vueMain.$store.state.Member.class.info.id) {
        console.log('未获取到用户信息');
        return;
    }
    let promises = [];
    let classId = vueMain.$store.state.Member.class.info.id;
    db.toCollection().modify(function (value) {
        if (value.class_id === classId) {
            promises.push(loadStrokeInfo(JSON.parse(value.data), value.data, classId));
        }
        // console.log('wtag', wtag++);
        delete this.value
    }).then(() => {
            Promise.all(promises)
                .then(data => {
                    let filterData = data.filter((value) => Object.keys(value).length);
                    if (filterData.length !== 0) {
                        let toPubJson = {
                            "id": uuid(),                //类型：String  必有字段  备注：消息id
                            "code": "0501",                //类型：String  必有字段  备注：0501
                            "packet-type": "command",                //类型：String  必有字段  备注：无
                            data: filterData
                        };
                        let toPub = JSON.stringify(toPubJson);
                        console.info(toPubJson);
                        window.client.publish("server/jiaofu", toPub, {qos: 2});
                        console.log('正在上报数据');
                    }
                });
        }
    );
    // fs.readdir(storePath, function (err, files) {
    //
    //     if (err) throw err;
    //     if (files.length > 0)
    //         console.info(files);
    //     for (let fname of files) {
    //         if ((parseInt(fname) + uploadInterval + 1000) > new Date().getTime()) {
    //
    //             continue
    //         }
    //         fs.readFile(storePath + '/' + fname, (err, data) => {
    //
    //             let strArr = data.toString().split("|").filter(jsonStr => {
    //                 if (!jsonStr) {
    //
    //                     return;
    //                 }
    //                 try {
    //                     let json = JSON.parse(jsonStr);
    //                     if (json['xy-dot-array'].length === 0) {
    //
    //                         return;
    //                     }
    //                     return true;
    //                 } catch (e) {
    //                     console.error(fname);
    //                     console.error(jsonStr);
    //                     console.error(e);
    //                 }
    //             });
    //             /** 加载轨迹的相关数据 **/
    //             promises = strArr.map(str => {
    //
    //                 return loadStrokeInfo(JSON.parse(str), str, classId);
    //             });
    //             /** 数据上报 **/
    //             Promise.all(promises)
    //                 .then(data => {
    //                     let filterData = data.filter((value) => Object.keys(value).length);
    //                     if (filterData.length !== 0) {
    //                         let toPubJson = {
    //                             "id": uuid(),                //类型：String  必有字段  备注：消息id
    //                             "code": "0501",                //类型：String  必有字段  备注：0501
    //                             "packet-type": "command",                //类型：String  必有字段  备注：无
    //                             data: filterData
    //                         };
    //                         let toPub = JSON.stringify(toPubJson);
    //                         console.info(toPubJson);
    //                         window.client.publish("server/jiaofu", toPub);
    //                         console.log('正在上报数据');
    //                     }
    //                     fs.unlink(storePath + '/' + fname, (err) => {
    //                     })
    //                 })
    //         })
    //     }
    // })
}, uploadInterval);


let prefixInteger = (num, length) => {
    return ("0000000000000000" + num).substr(-length);
};

export {WebSocketConfig, addDevice}
